package com.zjq.authoritysystem.utils;

import com.zjq.authoritysystem.entity.Department;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author Kimiaaaaa
 * @className DepartmentTreeUtil
 * @Description 部门树工具类
 * @date 2023-09-25 16:48
 */
public class DepartmentTreeUtil {

    /**
     * 生成部门树
     *
     * @param departmentList 部门列表
     * @param parentId       父级编号
     * @return
     */
    public static List<Department> makeDepartmentTree(List<Department> departmentList, Integer parentId) {
        List<Department> departments = new ArrayList<>();
        // 判断部门列表是否为空，如果不为空使用部门列表，否则创建集合对象
        Optional.ofNullable(departmentList).orElse(new ArrayList<>())
                .stream().filter(department -> department != null && department.getParentId() == parentId)
                .forEach(item -> {
                    Department department = new Department();
                    // 复制属性
                    BeanUtils.copyProperties(item, department);
                    //获取到每一个item的下级部门，通过递归生成部门树
                    List<Department> children = makeDepartmentTree(departmentList, department.getId());
                    department.setChildren(children);
                    departments.add(department);
                });
        return departments;
    }
}
